package com.wechat.weibo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wechat.weibo.dao.UserDao;
import com.wechat.weibo.entity.OpenidRes;
import com.wechat.weibo.entity.User;
import com.wechat.weibo.util.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginService {
    @Autowired(required = false)
    UserDao userDao;
//    获取用户openid并登录/注册
    public User login(String code,String userName,String img){
        HttpHeaders httpHeaders=new HttpHeaders();
        String res=HttpClient.sendGetRequest("https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=wx2154300dd5ab88bd&secret=82caa9e1884f2ddc86ab0e1f0040837e&js_code="+code
                +"&grant_type=authorization_code",null,httpHeaders);
//        json字符串解析器
        System.out.print(res);
        ObjectMapper objectMapper=new ObjectMapper();
        OpenidRes openidRes = null;
        try {
            openidRes=objectMapper.readValue(res, OpenidRes.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(openidRes==null)return null;
        String openid = openidRes.getOpenid();
        if(openid==null)return null;

        User tmpUsr=new User();
        tmpUsr.setOpenid(openid);
        tmpUsr.setUserName(userName);
        tmpUsr.setImg(img);
        User user=userDao.getUser(openid);
        if(user==null){
            userDao.newUser(tmpUsr);
            user=userDao.getUser(openid);
        }
        return user;
    }
    public User getUser(String openid){
        return userDao.getUser(openid);
    }
    public User reInfo(User user){
        userDao.reInfo(user);
        return userDao.getUser(user.getOpenid());
    }
    public List<User> search(String username){
        return userDao.search(username);
    }
}
